package org.agentframework.utils;

import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;

/**
 * @author wangjun
 **/
public class CodeParser {

    // 解析特定 block 的内容
    public static String parseBlock(String block, String text) {
        Map<String, String> blocks = parseBlocks(text);
        for (Map.Entry<String, String> entry : blocks.entrySet()) {
            if (entry.getKey().contains(block)) {
                return entry.getValue();
            }
        }
        return "";
    }

    // 解析文本，分割成不同的 blocks
    public static Map<String, String> parseBlocks(String text) {
        Map<String, String> blockDict = new LinkedHashMap<>();

        // 根据 "##" 分割文本
        String[] blocks = text.split("##");

        for (String block : blocks) {
            block = block.trim();
            if (block.isEmpty()) {
                continue;
            }

            String blockTitle, blockContent;
            if (!block.contains("\n")) {
                blockTitle = block;
                blockContent = "";
            } else {
                String[] parts = block.split("\n", 2);
                blockTitle = parts[0].trim();
                blockContent = parts[1].trim();
            }

            blockDict.put(blockTitle, blockContent);
        }
        return blockDict;
    }

    // 解析代码块
    public static String parseCode(String block, String text, String lang) {
        if (block != null && !block.isEmpty()) {
            text = parseBlock(block, text);
        }

        String pattern = "```" + lang + ".*?\\s+(.*?)```";
        Pattern regex = Pattern.compile(pattern, Pattern.DOTALL);
        Matcher matcher = regex.matcher(text);

        if (matcher.find()) {
            return matcher.group(1).trim();
        } else {
            System.err.println("Pattern not matched in text: " + text);
            return text; // 直接返回原文本，假设它是代码
        }
    }

    // 解析字符串值
    public static String parseStr(String block, String text, String lang) {
        String code = parseCode(block, text, lang);
        String[] parts = code.split("=");
        return parts.length > 1 ? parts[1].trim().replaceAll("['\"]", "") : code.trim();
    }

    // 解析文件列表
    public static List<String> parseFileList(String block, String text, String lang) {
        String code = parseCode(block, text, lang);
        String pattern = "\\s*(.*=.*)?(\\[.*\\])";

        Pattern regex = Pattern.compile(pattern, Pattern.DOTALL);
        Matcher matcher = regex.matcher(code);

        if (matcher.find()) {
            String tasksListStr = matcher.group(2);

            // 将字符串解析为 List
            return Arrays.stream(tasksListStr.replace("[", "").replace("]", "").split(","))
                    .map(String::trim)
                    .map(s -> s.replaceAll("['\"]", "")) // 去掉引号
                    .collect(Collectors.toList());
        } else {
            throw new RuntimeException("Failed to parse file list.");
        }
    }
}
